import Vue from "vue";
import Vuex from "vuex";
// 持久化存储
import persistedState from "vuex-persistedstate";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user: null,
    carList: [],
  },
  mutations: {
    saveUser(state, user) {
      state.user = user;
    },
    deleteUser(state) {
      state.user = null;
    },
    incrementQuantity(state, id) {
      let carList = state.carList;
      let idx = carList.findIndex((item) => item.id === id);
      state.carList[idx].quantity -= 1;
    },
    decrementQuantity(state, id) {
      let carList = state.carList;
      let idx = carList.findIndex((item) => item.id === id);
      state.carList[idx].quantity += 1;
    },
    alterQuantity(state, { id, quantity }) {
      let carList = state.carList;
      let idx = carList.findIndex((item) => item.id === id);
      state.carList[idx].quantity += quantity;
    },
    pushCarList(state, { id, imgUrl, title, price, quantity }) {
      // 如果购物车里面已经有了则不push了，直接加数量
      let carList = state.carList;
      let idx = carList.findIndex((item) => item.id === id);
      if (idx > -1) {
        this.commit("alterQuantity", { id, quantity });
        return;
      }
      let newItem = { id, imgUrl, title, price, quantity };
      state.carList.push(newItem);
    },
    delCar(state, id) {
      let index = state.carList.findIndex((item) => item.id === id);
      if (index > -1) {
        state.carList.splice(index, 1);
      }
    },
    deleteCarList(state) {
      state.carList = [];
    },
  },
  getters: {
    calAllTotal(state) {
      let ans = 0.0;
      state.carList.forEach((item) => {
        ans += item.price * item.quantity;
      });
      return parseFloat(ans).toFixed(2);
    },
  },
  actions: {},
  modules: {},
  plugins: [persistedState()],
});
